//
//  GroupDetailController.m
//  SouthChina
//
//  Created by creator_lq on 15/1/5.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "GroupDetailController.h"
#import "ContactDao.h"
#import "AddressBookLeftViewController.h"
#import "AddressBookViewController.h"
#import "MessageSessionDao.h"
#import "GroupPeopleInfoController.h"

@interface GroupDetailController ()<UITextFieldDelegate>
{
    Contact * contact;
    UITextField *setGroupName;
    UILabel * nameLabel;
}
@end

@implementation GroupDetailController

@synthesize groupid,qrCodeImage;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contactMessage:) name:CONTACT_CHANGE_BROADCAST object:nil];
    }
    return self;
}

- (void)contactMessage:(NSNotification *)notification{
    
    NSDictionary* msg = [notification object];
    NSString * pass_sessionId = [msg objectForKey:@"sessionID"];
    NSString * pass_businessId = [msg objectForKey:@"businessId"];
    NSString *thisSessId = [NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2G,groupid];

    if ([@"updateGrpName" isEqualToString:[msg objectForKey:@"businessId"]]) {
        if ([thisSessId isEqualToString:pass_sessionId]) {
            MessageSession *session = [MessageSessionDao queryMsgSessionById:thisSessId];
            self.lableTitle.text=session.title;
            nameLabel.text =session.title;
        }
    }
    // 解散群组或者删除好友，则要关闭当前界面
    else if(([@"dropGrp" isEqualToString:pass_businessId]||[@"endFriendship" isEqualToString:pass_businessId])
            &&[thisSessId isEqualToString:pass_sessionId]){
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    contact = [ContactDao getContactById:groupid];
    NSString * creatUser = [contact getValue:@"CREATE_USER"];
    
    [self addTitleBarWithBackBtn:contact.mNAME?contact.mNAME:@"" needReturn:YES];
    
    [self getJoinGrpQrCode];
    UIImage *img=[UIImage imageNamed:@"blue_btn_normal.png"];
    img=[img stretchableImageWithLeftCapWidth:20 topCapHeight:20];
    
    UIScrollView * groupScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    [self.view addSubview:groupScrollView];
    
    UIImageView * headImage = [[UIImageView alloc] initWithFrame:CGRectMake(20, 15, 50, 50)];
    headImage.image = [UIImage imageNamed:@"group"];
    headImage.layer.masksToBounds = YES;
    headImage.layer.cornerRadius = 8.0;
    [groupScrollView addSubview:headImage];
    
    nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30+headImage.frame.size.width,15, 180, 30)];
    nameLabel.text = contact.mNAME?contact.mNAME:@"";
    nameLabel.font = [UIFont boldSystemFontOfSize:15.0f];
    nameLabel.backgroundColor = [UIColor clearColor];
    [groupScrollView addSubview:nameLabel];
    
    UIView * founderView = [[UIView alloc] initWithFrame:CGRectMake(0, headImage.frame.size.height+25, SCREEN_WIDTH, 40)];
    founderView.backgroundColor = [UIColor whiteColor];
    [groupScrollView addSubview:founderView];

    UILabel * founderLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,9, 70, 21)];
    founderLabel.text = @"创建人：";
    founderLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [founderView addSubview:founderLabel];
    
    UILabel * founderNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(100,9, 200, 21)];
     founderNameLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [founderView addSubview:founderNameLabel];
    UIView * buttonBackView = [[UIView alloc] initWithFrame:CGRectMake(10, founderView.frame.origin.y+10+founderView.frame.size.height, SCREEN_WIDTH-20, 120)];
    buttonBackView.backgroundColor = [UIColor whiteColor];
    buttonBackView.layer.masksToBounds = YES;
    buttonBackView.layer.cornerRadius = 8.0;
    [groupScrollView addSubview:buttonBackView];

    setGroupName = [[UITextField alloc] initWithFrame:CGRectMake(10,10-(YNEW)/4, buttonBackView.frame.size.width-100, 30)];
    setGroupName.borderStyle=UITextBorderStyleNone;
    setGroupName.placeholder = @"修改群组名称";
    setGroupName.font = [UIFont boldSystemFontOfSize:14.0f];
    setGroupName.delegate = self;
    setGroupName.tag = 101;
    [buttonBackView addSubview:setGroupName];
    
    UIButton * modifyGroupName = [[UIButton alloc] initWithFrame:CGRectMake(setGroupName.frame.size.width+10,5,buttonBackView.frame.size.width-setGroupName.frame.size.width-20, 30)];
    [modifyGroupName addTarget:self action:@selector(modifyGroupName:) forControlEvents:UIControlEventTouchUpInside];
    [modifyGroupName setTitle:@"修改名称" forState:UIControlStateNormal];
    modifyGroupName.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [modifyGroupName setBackgroundImage:img forState:UIControlStateNormal];
    modifyGroupName.layer.masksToBounds = YES;
    modifyGroupName.layer.cornerRadius = 8.0;
    [buttonBackView addSubview:modifyGroupName];
    
    UIImageView * line = [[UIImageView alloc] initWithFrame:CGRectMake(0,modifyGroupName.frame.size.height+modifyGroupName.frame.origin.y+5, buttonBackView.frame.size.width, 1)];
    line.backgroundColor = [UIColor colorWithRed:236/255.0f green:235/255.0f blue:243/255.0f alpha:1];
    [buttonBackView addSubview:line];
    
    UIButton * addGroupManBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,line.frame.origin.y+2, (SCREEN_WIDTH)-20, 38)];
    [addGroupManBtn addTarget:self action:@selector(addGroupManBtn:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBackView addSubview:addGroupManBtn];
    
    UILabel * addGroupManLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,4, 200, 21)];
    addGroupManLabel.text = @"添加群成员";
    addGroupManLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [addGroupManBtn addSubview:addGroupManLabel];
    
    UIImageView * line2 = [[UIImageView alloc] initWithFrame:CGRectMake(0,addGroupManBtn.frame.size.height+addGroupManBtn.frame.origin.y, buttonBackView.frame.size.width, 1)];
    line2.backgroundColor = [UIColor colorWithRed:236/255.0f green:235/255.0f blue:243/255.0f alpha:1];
    [buttonBackView addSubview:line2];
    
    UIButton * lookGroupManBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,line2.frame.origin.y+2, (SCREEN_WIDTH)-20, 38)];
    [lookGroupManBtn addTarget:self action:@selector(lookGroupManBtn:) forControlEvents:UIControlEventTouchUpInside];
    [buttonBackView addSubview:lookGroupManBtn];
    
    UILabel * lookGroupManLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,4, 200, 21)];
    lookGroupManLabel.text = @"查看群成员";
    lookGroupManLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [lookGroupManBtn addSubview:lookGroupManLabel];
    
    UIView * messageRemaindView = [[UIView alloc] initWithFrame:CGRectMake(10, buttonBackView.frame.origin.y+10+buttonBackView.frame.size.height, SCREEN_WIDTH-20, 40)];
    messageRemaindView.layer.masksToBounds = YES;
    messageRemaindView.layer.cornerRadius = 8.0;
    messageRemaindView.backgroundColor = [UIColor whiteColor];
    [groupScrollView addSubview:messageRemaindView];
    UILabel * messageRemaindLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 9, 120, 21)];
    messageRemaindLabel.text = @"屏蔽消息提示";
    messageRemaindLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [messageRemaindView addSubview:messageRemaindLabel];
    UISwitch * allowStudentSwitchBtn = [[UISwitch alloc] initWithFrame:CGRectMake((SCREEN_WIDTH)-100+(YNEW), 5, 20, 20)];
    [allowStudentSwitchBtn addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    // 0不接受 1接收
    allowStudentSwitchBtn.on = [@"0" isEqualToString:contact.mIS_ACTIVATED];
    allowStudentSwitchBtn.enabled = [contact.mID containString:@"usergrp"];
    [messageRemaindView addSubview:allowStudentSwitchBtn];

    qrCodeImage = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH)/2-100, messageRemaindView.frame.origin.y+20+messageRemaindView.frame.size.height, 200, 200)];
    [groupScrollView addSubview:qrCodeImage];
    
    UILabel * qrCodeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,qrCodeImage.frame.origin.y+10+qrCodeImage.frame.size.height, (SCREEN_WIDTH)-20, 21)];
    qrCodeLabel.text = @"扫描二维码，直接加入该群组！";
    qrCodeLabel.textAlignment = NSTextAlignmentCenter;
    qrCodeLabel.backgroundColor = [UIColor clearColor];
    qrCodeLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [groupScrollView addSubview:qrCodeLabel];



    UIButton * dropButton = [[UIButton alloc] initWithFrame:CGRectMake(10,qrCodeLabel.frame.origin.y+30+qrCodeLabel.frame.size.height, (SCREEN_WIDTH)-20, 35)];
    [dropButton addTarget:self action:@selector(dropButton:) forControlEvents:UIControlEventTouchUpInside];
    [dropButton setTitle:@"解散群组" forState:UIControlStateNormal];
    [dropButton setBackgroundImage:img forState:UIControlStateNormal];
    [groupScrollView addSubview:dropButton];
    UIButton * exitButton = [[UIButton alloc] initWithFrame:CGRectMake(10,qrCodeLabel.frame.origin.y+30+qrCodeLabel.frame.size.height, (SCREEN_WIDTH)-20, 35)];
    [exitButton addTarget:self action:@selector(exitButton:) forControlEvents:UIControlEventTouchUpInside];
    [exitButton setTitle:@"退出群组" forState:UIControlStateNormal];
    [exitButton setBackgroundImage:img forState:UIControlStateNormal];
    [groupScrollView addSubview:exitButton];

    //只有群的创建者才能解散群，其他人只能退出群
    if ([DE.userId isEqualToString:creatUser]) {
        founderNameLabel.text = [DE getGlobalVar:LOGIN_USER_NAME];
        dropButton.hidden = NO;
        exitButton.hidden = YES;
    }else
    {
        Contact *creatId = [ContactDao getContactById:creatUser];
        founderNameLabel.text = creatId.mNAME;
        dropButton.hidden = YES;
        exitButton.hidden = NO;
    }

    groupScrollView.bounces = NO;
    [groupScrollView setBackgroundColor:[UIColor colorWithRed:236/255.0f green:235/255.0f blue:243/255.0f alpha:1]];
    [groupScrollView setShowsHorizontalScrollIndicator:NO];
    [groupScrollView setShowsVerticalScrollIndicator:NO];
    groupScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, dropButton.frame.origin.y+dropButton.frame.size.height+30);

    // Do any additional setup after loading the view.
}

-(void)getJoinGrpQrCode{
    
    NSDictionary *map = @{@"groupId":groupid};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [DE serverCall:@"getJoinGrpQrCode" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(success)
        {
            [self setQrCode:[data objectForKey:@"qrCodeSrc"]];
        }
        else{
            [self showAlerHUD:@"获取群组二维码失败！"];
        }
    }];
    
}

-(void)setQrCode:(NSString *)str
{
    NSURL *url= [NSURL URLWithString: [str hasPrefix:@"http"]?str:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,str]];
    qrCodeImage.layer.masksToBounds = YES;
    qrCodeImage.layer.cornerRadius = 8.0;
    [qrCodeImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];

}
-(void)dropButton:(id)sender
{
 
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [self removeThisSeesion];
    [DE serverCall:@"dropGrp" params:@{@"groupId":groupid} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
        
        if (success) {
            
            NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
            NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
            [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                if(success){
                    @try {
                        [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                        UIAlertView *aler =  [[UIAlertView alloc] initWithTitle:@"提示" message:@"解散群组成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [aler show];
                    }
                    @catch (NSException *exception) {
                        [self showAlerHUD:@"解散群组成功:本地更新失败！"];
                    }
                    
                }else{
                    [self showAlerHUD:@"解散群组成功：服务器同步失败！"];
                    
                }
                
            }];
            
        }else{
            
            [self showAlerHUD:@"解散群组失败!"];
        }
    }];
}
-(void)exitButton:(id)sender
{
     [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [self removeThisSeesion];
    [DE serverCall:@"exitGrp" params:@{@"groupId":groupid} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:NO];

        if (success) {
            
            NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
            NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
            [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                if(success){
                    @try {
                        [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                        UIAlertView *aler =  [[UIAlertView alloc] initWithTitle:@"提示" message:@"退出群组成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [aler show];
                        
                    }
                    @catch (NSException *exception) {
                        [self showAlerHUD:@"退出群组成功:本地更新失败！"];
                    }
                    
                }else{
                    [self showAlerHUD:@"退出群组成功：服务器同步失败！"];
                    
                }
                
            }];
            
        }else{
            
            [self showAlerHUD:@"退出群组失败!"];
        }
    }];
}

-(void)removeThisSeesion{
    
    NSString* sessionId =[NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2G,groupid];
    [MessageSessionDao deleteMessageSession:sessionId];
}

-(void)modifyGroupName:(id)sender
{
 
    [self.view endEditing:YES];

    if (setGroupName.text.length==0) {
        [self showAlerHUD:@"群组名不能为空"];
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [DE serverCall:@"updateGrpName" params:@{@"groupId":groupid,@"groupName":setGroupName.text} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if(success){
        
            MessageSession *mesSession = [MessageSessionDao queryMsgSessionById:[NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2G,groupid]];
            mesSession.title = setGroupName.text;
            mesSession.upate_time = [NSDate date];
            [MessageSessionDao updateMessageSession:mesSession];
            
            NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
            NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
            [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                
                if(success){
                    @try {
                        [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:mesSession.sess_id businessId:@"updateGrpName" sendout:YES];
                        [self showAlerHUD:@"修改群组名称成功！"];
                        nameLabel.text = setGroupName.text;
                        self.lableTitle.text =setGroupName.text;
                        
                    }
                    @catch (NSException *exception) {
                        [self showAlerHUD:@"修改群组名称成功:本地更新失败！"];
                    }
                    
                }else{
                    [self showAlerHUD:@"修改群组名称成功：服务器同步失败！"];
                    
                }
                
            }];
        }else{
            
            [self showAlerHUD:@"修改群组名称失败！"];

        }

        
    }];
}
-(void)addGroupManBtn:(id)sender
{
    
    AddressBookLeftViewController *colorsVC = [[AddressBookLeftViewController alloc] init];
    colorsVC.isCreatGroup = YES;
     AddressBookViewController *tabView = [[AddressBookViewController alloc] init];
    tabView.isCreatGroup =YES;
    tabView.passOrgContact  = contact;
    ICSDrawerController *creator = [[ICSDrawerController alloc] initWithLeftViewController:colorsVC
                                                                      centerViewController:tabView];
    creator.canDrawerMove = YES;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:creator animated:NO];
    
}
-(void)lookGroupManBtn:(id)sender
{
     
    GroupPeopleInfoController *controller = [[GroupPeopleInfoController alloc] init];
    controller.orgId = groupid;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:controller animated:NO];

}

-(void)switchAction:(id)sender
{
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    
    [DE serverCall:@"updateUsrGrpNotifyStatus" params:@{@"isNotify":isButtonOn?@"0":@"1",@"groupId":contact.mID} callback:
     ^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
         
         if (success && data && [data objectForKey:@"result"]) {
             contact.mIS_ACTIVATED = isButtonOn ? @"0" : @"1";
             [ContactDao updateContact:contact];
             MessageSession *mesSession = [MessageSessionDao queryMsgSessionById:[NSString stringWithFormat:@"%@_%@",MESSAGE_TYPE_P2G,groupid]];
             mesSession.isremind =  isButtonOn ? @"0" : @"1";
             [MessageSessionDao updateMessageSession:mesSession];
             
             [self showAlerHUD:@"设置成功！"];
         }else{
             [self showAlerHUD:@"设置失败！"];
             switchButton.on =!isButtonOn;
         }
        
    }];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end
